package jnpf.message.service.impl.open;

import cn.hutool.core.map.MapUtil;
import jnpf.constant.MsgCode;
import jnpf.constant.PermissionConst;
import jnpf.message.model.message.OpenBaseModel;
import jnpf.message.model.message.OpenDeptModel;
import jnpf.message.model.message.OpenRoleModel;
import jnpf.message.service.SynThirdInfoService;
import jnpf.message.service.ThirdOpenService;
import jnpf.message.util.SynThirdConsts;
import jnpf.permission.entity.*;
import jnpf.permission.service.*;
import jnpf.util.RandomUtil;
import jnpf.util.UserProvider;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
@Log4j2
@RequiredArgsConstructor
public class ThirdOpenRoleServiceImpl implements ThirdOpenService {

	private final SynThirdInfoService synThirdInfoService;

	private final UserProvider userProvider;

	private final OrganizeService organizeService;

	private final UserService userService;

	private final RoleService roleService;

	private final UserRelationService userRelationService;

	private final OrganizeRelationService organizeRelationService;

	@Override
	@Transactional(rollbackFor = Exception.class)
	public Object beforeProcess(OpenBaseModel openBaseModel, Map<String, OpenDeptModel> organizeMap) {
		OpenRoleModel roleModel = (OpenRoleModel) openBaseModel;
		OpenBaseModel.OperationType operationType = roleModel.getType();
		String description = "";
		String roleId = roleModel.getRoleId();
		try {
			switch (operationType) {
				case ADD:
				case EDIT:
				case ENABLE:
				case DISABLE:
					if (MapUtil.isNotEmpty(organizeMap)) {
						if (!organizeMap.containsKey(roleModel.getDeptId())) {
							description = "组织不存在";
							break;
						}
					} else {
						OrganizeEntity organizeEntity = organizeService.getById(roleModel.getDeptId());
						if (Objects.isNull(organizeEntity)) {
							description = "组织不存在";
							break;
						}
					}
					RoleEntity roleEntity = roleService.getInfo(roleId);
					if (Objects.isNull(roleEntity)) {
						roleEntity = new RoleEntity();
					}
					roleEntity.setEnCode(RandomUtil.getRandomCode());
					roleEntity.setSortCode(0L);
					roleEntity.setFullName(roleModel.getName());
					roleEntity.setGlobalMark(StringUtils.isBlank(roleModel.getDeptId()) ? 1 : 0);
					roleEntity.setId(roleId);
					roleEntity.setEnabledMark(operationType == OpenBaseModel.OperationType.DISABLE ? 0 : 1);
					roleEntity.setOrgId(roleModel.getDeptId());
					return roleEntity;
				case DELETE:
					// 当角色绑定用户不让其删除
					if (userRelationService.existByObj(PermissionConst.ROLE, roleId)) {
						description = MsgCode.FA024.get();
						break;
					}
					RoleEntity entity = roleService.getInfo(roleId);
					if (entity != null) {
						List<UserRelationEntity> userRelList = userRelationService.getListByObjectId(roleId);
						if (userRelList.size() > 0) {
							description = MsgCode.FA024.get();
							break;
						}
						for (UserRelationEntity entity1 : userRelList) {
							UserEntity entity2 = userService.getById(entity1.getUserId());
							if (entity2 != null) {
								String newRoleId = entity2.getRoleId().replace(roleId, "");
								if (entity2.getRoleId().contains(roleId)) {
									if (newRoleId.length() != 0 && newRoleId.substring(0, 1).equals(",")) {
										entity2.setRoleId(newRoleId.substring(1));
									} else if (newRoleId.length() != 0) {
										entity2.setRoleId(newRoleId.replace(",,", ","));
									}
								}
							}
						}
						// 删除所有用户角色关联
						userRelationService.deleteAllByObjId(roleId);
						// 删除所有组织角色关联
						organizeRelationService.deleteAllByRoleId(roleId);
						roleService.delete(entity);
					}
			}
		} catch (Exception e) {
			description = e.getMessage();
			throw e;
		} finally {
			saveSynThirdInfoEntity(operationType, SynThirdConsts.DATA_TYPE_ROLE, roleId, StringUtils.isBlank(description) ? 2 : 1, description, synThirdInfoService, userProvider);
		}
		return null;
	}


	@Override
	@Transactional(rollbackFor = Exception.class)
	public void afterProcess(List<Object> result) {
		List<RoleEntity> roleEntities = result.stream().map(e -> (RoleEntity) e).filter(Objects::nonNull).collect(Collectors.toList());
		roleService.saveOrUpdateBatch(roleEntities);

		List<OrganizeRelationEntity> organizeRelationEntityList = roleEntities.stream()
				.filter(Objects::nonNull)
				.filter(e -> StringUtils.isNotBlank(e.getOrgId()))
				.map(e -> {
					//删除原有的组织关系
					organizeRelationService.deleteAllByRoleId(e.getId());
					// 添加与组织的关联关系
					OrganizeRelationEntity organizeRelationEntity = new OrganizeRelationEntity();
					organizeRelationEntity.setId(RandomUtil.uuId());
					organizeRelationEntity.setOrganizeId(e.getOrgId());
					organizeRelationEntity.setObjectType(PermissionConst.ROLE);
					organizeRelationEntity.setObjectId(e.getId());
					return organizeRelationEntity;
				}).collect(Collectors.toList());
		organizeRelationService.saveOrUpdateBatch(organizeRelationEntityList);
	}
}
